//
//  UploadAvatarViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "UploadAvatarViewController.h"

@interface UploadAvatarViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) UIImageView *avatarView;
@property (nonatomic, strong) UILabel *avatarLabel;
@property (nonatomic, strong) UIImageView *nicknameView;
@property (nonatomic, strong) UITextField *nicknameTF;
@property (nonatomic, strong) UIImageView *nicknameIcon;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UIImagePickerController * imagePicker; // 系统图片框架


@end

@implementation UploadAvatarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    if ([DTCEXRACT_OBJECT(AVATAR) isEqualToString:@"YES"] && [DTCEXRACT_OBJECT(ISNICKNAME) isEqualToString:@"YES"] && !DTCEXRACT_OBJECT(SEX)) {
//        ChooseSexViewController *vc = [[ChooseSexViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
}

- (void)refreshBaseControlValue
{
    if (![DTCEXRACT_OBJECT(REGISTER) isEqualToString:@"1"]) {
        [self setLeftButtonImage:[UIImage imageNamed:@"nav_back_white_nor"]];
    }
    [self hideNavigationBottomLine];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    
    [self layoutSubviews];
    //    [self.view addSubview:self.iconImageView];
}



#pragma mark -- 代理 
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"buttonindex===%ld",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            
        {
            [self formcamera];
            
        }
            break;
        case 1:
            
        {
            [self formphoto];
        }
            break;
            
        default:
            break;
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        _imagePicker = imagePicker;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    _imagePicker = imagePicker;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
// 完成选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    self.avatarView.image = image;

    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    SetUserInfoApi * setApi = [[SetUserInfoApi alloc] initWithInfo:@{@"image":PorPath}];
    [setApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        if ([[request responseJSONObject][@"errcode"] intValue] == 0) {
            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                [userInfoApi analyseResponseObject];
//                [self.tableView reloadData];
                DTCSAVE_OBJECT(@"YES", AVATAR);
            } failure:^(YTKBaseRequest *request) {
                [SVProgressHUD showErrorWithStatus:@"请求超时"];
            }];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showInfoWithStatus:@"请求超时"];
    }];
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- 事件
- (void)didClickAvatarView {
    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄照片" otherButtonTitles:@"相册", nil] ;
    [sheet showInView:self.view];
}

- (void)didClickNextButton {
    if (![DTCEXRACT_OBJECT(AVATAR) isEqualToString:@"YES"]) {
        [SVProgressHUD showErrorWithStatus:@"请上传头像"];
        return;
    }
    
    if (self.nicknameTF.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"昵称不能为空"];
        return;
    }
    if (self.nicknameTF.text.length > 10) {
        [SVProgressHUD showInfoWithStatus:@"昵称长度不能超过20个"];
        return;
    }
    
    if ([NSString isContainsTwoEmoji:self.nicknameTF.text] ) {
        [SVProgressHUD showInfoWithStatus:@"昵称不能使用表情"];
        return;
    }
//    NSString *string = [self.nicknameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *string = [self.nicknameTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    SetUserInfoApi *api = [[SetUserInfoApi alloc]initWithInfo:@{@"nickname":string}];
    [api startWithCompletionAnimation:YES andBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        DTCSAVE_OBJECT(@"YES", AVATAR);
        DTCSAVE_OBJECT(@"YES", ISNICKNAME);
        DTCSAVE_OBJECT(@"2", REGISTER);
        ChooseSexViewController *vc = [[ChooseSexViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        //        [self.navigationController popViewControllerAnimated:YES];
    } backfailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    } requestFailure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];
    
    [self nextStep];
    
}

- (void)nextStep {
    
    
}


#pragma mark -- 加载视图
- (void) layoutSubviews {
    [self.avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(px1920Height(273));
        make.centerX.equalTo(self.view);
        make.width.height.mas_equalTo(px1080Width(326));
    }];
    
    [self.avatarLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatarView.mas_bottom).with.offset(px1920Height(44));
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(px1920Height(52));
        make.width.equalTo(self.view);
    }];
    
    [self.nicknameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avatarLabel.mas_bottom).with.offset(px1920Height(195));
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).with.offset(px1080Width(100));
        make.right.equalTo(self.view).with.offset(-px1080Width(100));
        make.height.mas_equalTo(px1920Height(136));
    }];
    
    [self.nicknameIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.nicknameView);
        make.left.mas_equalTo(px1080Width(40));
        make.width.height.mas_equalTo(px1920Height(68));
    }];
    
    [self.nicknameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.nicknameView);
        make.left.equalTo(self.nicknameIcon.mas_right).with.offset(px1080Width(40));
        make.right.equalTo(self.nicknameView).with.offset(px1080Width(40));
        make.height.mas_equalTo(px1920Height(68));
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nicknameView.mas_bottom).with.offset(px1920Height(530));
        make.left.equalTo(self.view).with.offset(px1080Width(100));
        make.right.equalTo(self.view).with.offset(-px1080Width(100));
        make.height.mas_equalTo(px1920Height(136));
    }];
}



#pragma mark -- 懒加载
- (UIImageView *)avatarView
{
    if(!_avatarView)
    {
        UIView *superView = self.view;
        _avatarView = [[UIImageView alloc]init];
        _avatarView.image = [UIImage imageNamed:@"icon_user"];
        _avatarView.layer.masksToBounds = YES;
        _avatarView.layer.cornerRadius = px1080Width(326) / 2 ;
        _avatarView.userInteractionEnabled = YES;
        [_avatarView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickAvatarView)]];
        [superView addSubview:_avatarView];
    }
    return _avatarView;
}

- (UILabel *)avatarLabel
{
    if(!_avatarLabel)
    {
        UIView *superView = self.view;
        _avatarLabel = [[UILabel alloc]init];
        [superView addSubview:_avatarLabel];
        [_avatarLabel setFont:[UIFont systemFontOfSize:15]];
        _avatarLabel.textAlignment = NSTextAlignmentCenter;
        [_avatarLabel setTextColor:[UIColor whiteColor]];
        _avatarLabel.text = @"上传头像";
    }
    return _avatarLabel;
}

- (UIImageView *)nicknameView
{
    if(!_nicknameView)
    {
        UIView *superView = self.view;
        _nicknameView = [[UIImageView alloc]init];
        _nicknameView.image = [UIImage imageNamed:@"nickname_view"];
        _nicknameView.userInteractionEnabled = YES;
        [superView addSubview:_nicknameView];
    }
    return _nicknameView;
}

- (UIImageView *)nicknameIcon
{
    if(!_nicknameIcon)
    {
        _nicknameIcon = [[UIImageView alloc]init];
        [self.nicknameView addSubview:_nicknameIcon];
        _nicknameIcon.image = [UIImage imageNamed:@"icon_nickname"];
    }
    return _nicknameIcon;
}

- (UITextField *)nicknameTF
{
    if(!_nicknameTF)
    {
        UIView *superView = self.view;
        _nicknameTF = [[UITextField alloc]init];
        _nicknameTF.placeholder = @"请输入昵称（2-16字符以内）";
        [_nicknameTF setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        _nicknameTF.tintColor = [UIColor whiteColor];
        _nicknameTF.textColor = [UIColor whiteColor];
        [superView addSubview:_nicknameTF];
    }
    return _nicknameTF;
}

- (UIButton *)nextButton
{
    if(!_nextButton)
    {
        _nextButton = [[UIButton alloc]init];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton setTitleColor:[UIColor colorWithHexString:@"#3E76F6"] forState:UIControlStateNormal];
        //        [_registerButton.titleLabel setFont:<#(UIFont * _Nullable)#>];
        [_nextButton setBackgroundImage:[UIImage imageNamed:@"button_next_nor"] forState:UIControlStateNormal];
        [_nextButton setBackgroundImage:[UIImage imageNamed:@"button_next_sel"] forState:UIControlStateHighlighted];
        [_nextButton addTarget:self action:@selector(didClickNextButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_nextButton];
    }
    return _nextButton;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
